package com.ddiviewer;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

/*
 * New DDIWebView
 */
public class DDIWebView extends Activity {
	
	String			baseUrl;
	String			prefFileName;
	WebView 		wv;
	WebSettings 	ws;
	AlertDialog 	alertDialog;
	ProgressDialog 	progressBar;
	
	String				url				= new String();
	String				responseString	= new String();
	List<NameValuePair>	myPostData  	= new ArrayList<NameValuePair>();
	
	
	/*
	 * onCreate - Override
	 *   Get login cookies and put them into the CookieManager
	 *   Start WebView and view the page
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);
        
		// global strings
		baseUrl = getResources().getString(R.string.baseUrl);
        prefFileName = getResources().getString(R.string.prefFileName);
        
        
        url = new String(baseUrl + SearchTab.save.getTab().toLowerCase() + ".aspx?id=" + SearchTab.save.getID());
        wv = (WebView) findViewById(R.id.web);
        ws = wv.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setSavePassword(true);
        ws.setSaveFormData(true);
        ws.setBuiltInZoomControls(true);
        ws.setSupportZoom(true);

        if (CookieManager.getInstance().getCookie("www.wizards.com") != null) {
        	Log.i("Skipping auth", "Cookie already present");
        } else {
        	Log.i("authenticating", "Cookie not present");
        	checkMyConnection(url);        
        }
        
        wv.setWebViewClient(new WebViewClient() {
        	//@Override
        	@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //Log.i("DDIWebView", "Processing webview url click...");
                view.loadUrl(url);
                return true;
            }

    		@Override
    		public void onPageFinished(WebView view, String url) {
    			//if (progressBar.isShowing()) progressBar.dismiss();
    		}

    		@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(DDIWebView.this, "Received Error: " + description, Toast.LENGTH_SHORT).show();
                alertDialog.setTitle("Error");
                alertDialog.setMessage(description);
                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        return;
                    }
                });
                alertDialog.show();
            }
        });

        wv.loadUrl(url);
	}
	
	
	/*
	 * checkMyConnection
	 *   Get login cookies
	 */
	private void checkMyConnection(String findURL) {
		HttpGet request;
		HttpPost post;
		DefaultHttpClient client;
		HttpResponse response;
		String action = new String();

		//CookieManager.getInstance().setAcceptCookie(true);
		
		try {
			request = new HttpGet(findURL);
			client = new DefaultHttpClient();
			response = client.execute(request);
		    
			responseString = new String(EntityUtils.toString(response.getEntity()));
			action = parseAction(responseString);
			
			if (action.contains("login.aspx")) {
				Log.e("CREATING NEW LOGIN", "CREATING NEW LOGIN");
				SharedPreferences sp = getSharedPreferences(prefFileName, MODE_PRIVATE);
				myPostData.add(new BasicNameValuePair("email", sp.getString("username", null)));
				myPostData.add(new BasicNameValuePair("password", sp.getString("password", null)));
				
				parseFormData(responseString);
			} else {
				Log.i("EXISTING LOGIN", "EXISTING LOGIN");
			}
			
			post = new HttpPost(action);
			UrlEncodedFormEntity urlefe = new UrlEncodedFormEntity(myPostData, "UTF-8");
			post.setEntity(urlefe);
			response = client.execute(post);
			
			// Send cookies everywhere
			List<Cookie> ck = client.getCookieStore().getCookies();
	        if (ck != null) {
	        	for (Cookie cookie : ck) {
	        		String cookieString =  cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();
	        		CookieManager.getInstance().setCookie(cookie.getDomain(), cookieString);
	        	}
	        	CookieSyncManager.getInstance().sync();
	        }
	        
		} catch (Exception e) {
			Log.e("EXCEPTION", e.getMessage());
		}
		
	}
	
	
	/*
	 * parseAction
	 */
	private String parseAction(String s) {
		int start = s.indexOf("action=");
		String action = s.substring(start + 8);
		int end = action.indexOf("\"");
		return baseUrl + action.substring(0, end);
	}

	
	/*
	 * parseFormData
	 */
	private void parseFormData(String source) {
		try {

			while (source.contains("<input")) {
				// First grep out the <input> tag.
				int start = source.indexOf("<input");
				String input = source.substring(start);
				int end = input.indexOf('>');
				input = input.substring(0, end + 1);
				source = source.substring(start + end);

				// Now grep the type= attribute from the input tag
				if ((start = input.indexOf("type=")) != -1) {
					String type = input.substring(start + 6);
					end = type.indexOf("\"");
					type = type.substring(0, end);
					if (type.equals("text") || type.equals("password"))
						continue; // we can't deal with text fields here.
				}

				// Now grep the name= attribute from the input tag
				start = input.indexOf("name=");
				String name = input.substring(start + 6);
				end = name.indexOf("\"");
				name = name.substring(0, end);

				// Now grep the value= attribute from the input tag
				start = input.indexOf("value=");
				String value = input.substring(start + 7);
				end = value.indexOf("\"");
				value = value.substring(0, end);

				myPostData.add(new BasicNameValuePair(name, value));
		    }
		} catch (Exception e) {
		      Log.e("ERROR", "Error parsing login source for form data: " + e);
		}
	}
	
}

